#include "wndhelper.h"

#include <windows.h>
#include <Dwmapi.h>
#include <QRect>

WndHelper::WndHelper(QObject *parent) : QObject(parent)
{
    
}

bool WndHelper::getSmallestWindowFromCursor(QRect &windowRect)
{
    HWND hwnd;
    POINT pt;
    // 获得当前鼠标位置
    ::GetCursorPos(&pt);
    /// 获得当前位置桌面上的子窗口
    hwnd = ::ChildWindowFromPointEx(::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE);
    if (hwnd != NULL) {
        HWND temp_hwnd;
        temp_hwnd = hwnd;
        while (true) {
            ::GetCursorPos(&pt);
            ::ScreenToClient(temp_hwnd, &pt);
            temp_hwnd = ::ChildWindowFromPointEx(temp_hwnd, pt, CWP_SKIPINVISIBLE);
            if (temp_hwnd == NULL || temp_hwnd == hwnd)
                break;
            hwnd = temp_hwnd;
        }
        RECT temp_window;
        ::GetWindowRect(hwnd, &temp_window);
        if(QSysInfo::windowsVersion()>QSysInfo::WV_WINDOWS7)
        {
            /// 在Win10中GetWindowRect获取的区域比包含部分不可见边界（左、右、下阴影），因此比实际窗口大。
            /// 调用DwmGetWindowAttribute可以屏蔽这种差异
            ::DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &temp_window, sizeof(RECT));
        }
        /// 如果窗口最大化
        if(::IsZoomed(hwnd))
        {
            //获取屏幕工作区(即除去任务栏的区域)
            ::SystemParametersInfo(SPI_GETWORKAREA, 0, &temp_window, 0);

        }

        windowRect.setRect(temp_window.left,
                           temp_window.top,
                           temp_window.right - temp_window.left,
                           temp_window.bottom - temp_window.top);
        return true;
    }
    
    return false;
}
